<template>
  <div class="page-buy">
    <div class="body-position">
      <div class="page-position">
        <i-form>
          <Form-item>
            <div class="tips">
              <p>
                <span class="confirm-order">确认订单信息</span
                ><span class="tips-info"
                  >请在2小时内完成支付，否则订单会被自动取消</span
                >
              </p>
            </div>
          </Form-item>
          <Form-item>
            <!-- 肖像昵称 -->
            <div class="portrait">
              <div class="portrait-left"><img :src="user_info.avatar" /></div>
              <div class="portrait-right">
                <div class="user-buy">
                  {{ $t("locale.pc.mycourse.coursebuy.t2") }}:{{
                    user_info.account
                  }}
                </div>
                <div class="user-tips">
                  {{ $t("locale.pc.mycourse.coursebuy.t3") }}
                </div>
              </div>
            </div>
          </Form-item>
          <div class="online"></div>
          <!-- 课程信息 -->
          <Form-item>
            <div class="ordermes">
              <p class="order-title">
                {{ $t("locale.pc.mycourse.coursebuy.t4") }}
              </p>
              <div class="order-msg">
                <div class="course-img">
                  <img :src="course_obj.iconPath" />
                </div>
                <div class="course-info">
                  <div class="course-name">{{ course_obj.courseName }}</div>
                  <div class="course-price">
                    <div>{{ course_obj.majorName }}</div>
                    <div>￥{{ course_obj.price }}</div>
                  </div>
                </div>
                <!-- <h1>{{ course_obj.courseName }}</h1>
                  <h2>
                    {{ course_obj.majorName }}
                    <span
                      >{{ $t("locale.pc.mycourse.coursebuy.currency")
                      }}{{
                        course_obj.isFree
                          ? 0
                          : course_obj.isDiscount
                          ? course_obj.discountPrice
                          : course_obj.price
                      }}</span
                    >
                  </h2> -->
              </div>
            </div>
            <!-- 支付方式 -->
          </Form-item>
          <div class="pay-list">
            <span style="margin-right:20px;">支付方式</span>
            <RadioGroup v-model="payType">
              <Radio :label="1">
                <span class="ye-pay">
                  <img src="/img/pc/ye.png" alt="" />
                  余额
                </span>
              </Radio>
              <Radio :label="2" v-if="!course_obj.isFree">
                <span class="wx-pay">
                  <img src="/img/pc/weixin.png" alt="" />
                  微信
                </span>
              </Radio>
              <Radio :label="3" v-if="!course_obj.isFree">
                <span class="zfb-pay">
                  <img src="/img/pc/zhifubao.png" alt="" />
                  支付宝
                </span>
              </Radio>
            </RadioGroup>
          </div>
          <Form-item>
            <div class="submitform">
              <i-col span="19">
                <p class="p1">
                  {{ $t("locale.pc.mycourse.coursebuy.t5") }}
                  <b>{{ $t("locale.pc.mycourse.coursebuy.currency") }}</b>
                  <span>{{
                    Number(
                      course_obj.isFree
                        ? 0
                        : course_obj.isDiscount
                        ? course_obj.discountPrice
                        : isMemberFree
                        ? 0
                        : !is_member
                        ? course_obj.price
                        : user_member.memberLevel === 0
                        ? course_obj.smallMemberPrice
                        : user_member.memberLevel === 1
                        ? course_obj.middleMemberPrice
                        : user_member.memberLevel === 2
                        ? course_obj.highMemberPrice
                        : 0
                    ).toFixed(2)
                  }}</span>
                </p>
                <!-- <p class="p2">
                  提交订单则表示您同意
                  <a href>《北京泓深课堂用户付费协议》</a>
                </p> -->
              </i-col>
              <i-col span="5">
                <i-button @click="handlePay">{{
                  $t("locale.pc.mycourse.coursebuy.t6")
                }}</i-button>
              </i-col>
            </div>
          </Form-item>
        </i-form>
      </div>
    </div>
    <Modal v-model="is_show_wechat_pay" :title="$t('locale.pc.personal.t74')">
        <div style="text-align:center;">
          <img :src="wechat_pay_qr" />
        </div>
      </Modal>
  </div>
</template>

<script>
import { getCourse } from "~/api/course";
import { baseUrl, socketUrl } from "~/config/conf";
import { saveOrder,generateOrder,getCourseBuyToPcAlipay } from "~/api/order";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  data() {
    return {
      course_obj: {}, //课程
      major_obj: {}, //专业
      teacher_obj: {}, //教师
      payType: 1,
      wechat_pay_qr:"",
      is_show_wechat_pay:false,
      websock: null,
      timer: null, //节流计时器
      socketFailedCount: 0, //socket重连计数器
      orderNo:"",
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      token(state) {
        return state.token;
      },
      user_member(state) {
        return state.member_info;
      },
      member_discount(state) {
        return state.member_discount;
      }
    }),
    isMemberFree() {
      if (
        this.member_discount &&
        JSON.stringify(this.member_discount) !== "{}"
      ) {
        if (
          this.member_discount.majorIds.includes(this.course_obj.majorId) ||
          this.member_discount.courseIds.includes(this.course_obj.id)
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    course_id() {
      return this.$route.query.id;
    }
  },
  methods: {
    ...mapActions(["initMember","initBuyRecord"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST"
    ]),
    initWebSocket() {
      if (process.client) {
        if ("WebSocket" in window) {
          //初始化weosocket
          const wsuri = socketUrl + "buyOrderInfo/" + this.orderNo;
          this.websock = new WebSocket(wsuri);
          this.websock.onmessage = this.websocketonmessage;
          this.websock.onopen = this.websocketonopen;
          this.websock.onerror = this.websocketonerror;
          this.websock.onclose = this.websocketclose;

          window.addEventListener("beforeunload", this.closeConnection, false);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t134"));
        }
      }
    },
    websocketonopen() {
      //连接建立之后执行send方法发送数据
      clearTimeout(this.timer);
      this.timer = null;
      this.socketFailedCount = 0;
    },
    websocketonerror() {
      //连接建立失败重连
      console.log("socket连接失败！");
      this.retryConnectSocket();
    },
    websocketonmessage(e) {
      //数据接收
      console.log("收到socket:", e);
      console.log(e.data || e);
      try {
        const result = JSON.parse(e.data);
        if (result.code == 200) {
          let courseId = result.data.productId;
          // 付款成功
          this.pay_success = true;
          this.is_show_wechat_pay = false;
          this.paySuccess(courseId);
        } else {
          this.$Message.error(this.$t("locale.pc.personal.t128"));
        }
      } catch (e) {
        console.log(e);
      }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    async websocketclose(e) {
      //关闭
      console.log("断开连接", e);
      this.retryConnectSocket();
    },
    closeConnection() {
      return new Promise((res, rej) => {
        try {
          window.removeEventListener("beforeunload", this.closeConnection);
          this.websock && this.websock.close();

          if(this.timer){
            clearTimeout(this.timer);
            this.timer = null;
            this.socketFailedCount = 0;
          }
        } catch (e) {
          console.log("关闭socket错误：", e);
        }
        res();
      }).then();
    },
    retryConnectSocket() {
      this.debounce(async () => {
        this.socketFailedCount = this.socketFailedCount + 1;
        if (this.socketFailedCount < 10) {
          await this.closeConnection();
          this.initWebSocket();
        } else {
          console.info("websocket fail to connection , please retry later!");
          this.timer = null;
        }
      }, 3000);
    },
    debounce(fn, wait) {
      return !(() => {
        if (this.timer !== null) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(fn, wait);
      })();
    },
    async getData() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getCourse({
          id: this.course_id
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            // this.course_obj = data.rows[0];
            // 加一层折扣时间的判断,不在折扣时间内判定为不是折扣课程
            let course = data.rows[0];
            let currentTime = new Date().getTime();
            if(!(course.isDiscount == 1 && currentTime >= course.discountStartTime && course.discountEndTime >= currentTime)){
              this.course_obj = {
                ...course,
                isDiscount:0
              }
            }else{
              this.course_obj = course;
            }
          }
        } else {
          this.$Message.error(
            this.$t("locale.pc.mycourse.coursebuy.t7") + result &&
              result.data &&
              result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    async handlePay() {
      let __price__ = Number(
        this.course_obj.isFree
          ? 0
          : this.course_obj.isDiscount
          ? this.course_obj.discountPrice
          : this.isMemberFree
          ? 0
          : !this.is_member
          ? this.course_obj.price
          : this.user_member.memberLevel === 0
          ? this.course_obj.smallMemberPrice
          : this.user_member.memberLevel === 1
          ? this.course_obj.middleMemberPrice
          : this.user_member.memberLevel === 2
          ? this.course_obj.highMemberPrice
          : 0
      ).toFixed(2);
      if (this.payType == 1) {
        console.log("余额支付");
        const successFun = () => {
          this.$Modal.confirm({
            title: this.$t("locale.pc.mycourse.coursebuy.t8"),
            content:
              this.$t("locale.pc.mycourse.coursebuy.t9") +
              (__price__ - this.user_info.balance) +
              this.$t("locale.pc.mycourse.coursebuy.t11"),
            okText: this.$t("locale.pc.mycourse.coursebuy.t10"),
            onOk: () => {
              this.$router.push({
                path: "personal?action=my_account",
                query: {
                  num: __price__ - this.user_info.balance,
                  rdurl: this.$route.fullPath
                }
              });
            }
          });
        };
        this.$Modal.confirm({
          title: this.$t("locale.pc.mycourse.coursebuy.t12"),
          content:
            this.$t("locale.pc.mycourse.coursebuy.t13") +
            __price__ +
            this.$t("locale.pc.mycourse.coursebuy.t14"),
          onOk: async () => {
            // console.log(__price__, this.user_info.balance);
            if (__price__ > this.user_info.balance) {
              this.$nextTick(() => {
                setTimeout(() => {
                  successFun();
                }, 500);
              });
            } else {
              this.SET_IS_LOADING(true);
              let params = {
                courseId: this.course_id,
                userId: this.user_info.id,
                price: this.turnString(__price__),
                ip: returnCitySN.cip
              };
              let result = await saveOrder(params);
              if (result && result.data && result.data.code == 200) {
                const {
                  balance,
                  id,
                  courseId,
                  userId,
                  deleted
                } = result.data.data;
                let update_obj = {
                  balance
                };
                let course_update_obj = {
                  id,
                  courseId,
                  userId,
                  deleted
                };
                this.UPDATE_USERINFO(update_obj);
                this.UPDATE_BUYRECORD_LIST(course_update_obj);
                this.SET_IS_LOADING(false);
                this.$Message.success(
                  this.$t("locale.pc.mycourse.coursebuy.t15")
                );
                this.$router.replace("/coursedetail?id=" + this.course_id);
              } else if (result && result.data && result.data.code == 1001) {
                this.SET_IS_LOADING(false);
                this.$Message.warning(result.data.msg);
              } else if (result && result.data && result.data.code == 420) {
                this.SET_IS_LOADING(false);
                this.$Message.error(
                  this.$t("locale.pc.mycourse.coursebuy.t16")
                );
              } else {
                this.SET_IS_LOADING(false);
                this.$Message.error(
                  this.$t("locale.pc.mycourse.coursebuy.t17")
                );
              }
            }
          },
          onCancel: () => {
            this.$Message.success(this.$t("locale.pc.mycourse.coursebuy.t18"));
          }
        });
      } else if (this.payType == 2) {
        // this.SET_IS_LOADING(true);
        let params = {
          courseId: this.course_id,
          userId: this.user_info.id,
          price: this.turnString(__price__),
          ip: returnCitySN.cip,
          type:1,
          payType:2
        };
        let result = await generateOrder(params);
        if(result && result.data && result.data.code == 200){
          const { orderNo } = result.data.data;
          this.orderNo = orderNo;
          this.wechat_pay_qr = `${baseUrl}/buyOrderInfo/wx/pc?orderNo=${orderNo}`;
          this.initWebSocket();
          this.is_show_wechat_pay = true;
          // console.log(result.data.data);
        }else{
          this.$Message.error("系统错误");
        }
        console.log("微信支付");
      } else if (this.payType == 3) {
        let params = {
          courseId: this.course_id,
          userId: this.user_info.id,
          price: this.turnString(__price__),
          ip: returnCitySN.cip,
          type:1,
          payType:3
        };
        let result = await generateOrder(params);
        if(result && result.data && result.data.code == 200){
          const { orderNo } = result.data.data;
          this.orderNo = orderNo;
          let resultPay = await getCourseBuyToPcAlipay(this.orderNo);
          if (resultPay && resultPay.data && resultPay.data.code == 200) {
            window.location.href = resultPay.data.data;
          } else {
            this.$Message.error(
              this.$t("locale.pc.personal.t128") + resultPay.data
                ? resultPay.data.msg
                : null
            );
          }
        }else{
          this.$Message.error("系统错误");
        }
        console.log("支付宝支付");
        
      } else {
        this.$Message.warning("请选择您的支付方式");
      }
      return;
    },
    paySuccess(courseId){
      let id = courseId || this.course_id;
      this.initBuyRecord();
      this.$Message.success("购买成功");
      this.$router.replace("/coursedetail?id=" + id);
    }
  },
  deactivated(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  destroyed(){
    this.timer = null;
    this.socketFailedCount = 0;
    this.closeConnection();
  },
  created() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/login");
        return;
      }
      this.getData();
      this.initMember();
      if(this.$route.query.isSuccess == 1){
        // 支付成功--获取课程id
        this.pay_success = true;
        this.paySuccess();
      }
    }
    // this.initWebSocket();

  }
};
</script>

<style lang="scss">
.ivu-form-item {
  margin-bottom: 0;
}
.ivu-form-item-content {
  line-height: normal;
}
.page-buy {
  width: 100%;
  height: 100%;
  padding: 10px 0px;
  .ivu-radio-group {
    display: flex;
  }
  .ivu-radio-wrapper.ivu-radio-group-item {
    display: flex;
    align-items: center;
  }
  .pay-list {
    margin: 30px 0 22px;
    padding: 0 50px;
    font-size: 16px;
    display: flex;
    align-items: center;
    .ye-pay,
    .wx-pay,
    .zfb-pay {
      padding: 0px 11px;
      margin-left: 15px;
      border-radius: 4px;
      font-size: 16px;
      display: inline-flex;
      align-items: center;
    }
    .ye-pay {
      border: 1px solid #515a6e;
      img {
        width: 30px;
        height: 30px;
        display: block;
      }
      margin-right: 20px;
    }
    .wx-pay {
      border: 1px solid #00c800;
      margin-right: 20px;
    }
    .zfb-pay {
      border: 1px solid #2194d3;
    }
  }
  .body-position {
    margin-bottom: 10px;
    width: 1000px;
    height: 690px;

    margin: 0 auto;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(255, 255, 255, 0);
    .page-position {
      font-size: 14px;
      width: 100%;
      height: 100%;
      .online {
        width: 100%;
        height: 1px;
        background-color: #e9ebf0;
      }
      .tips {
        width: 100%;
        height: 80px;
        line-height: 80px;
        background-color: #e9ebf0;
        box-sizing: border-box;
        padding: 0 50px;
        .confirm-order {
          font-size: 16px;
          font-weight: bold;
          color: #43474d;
        }
        .tips-info {
          margin-left: 20px;
          font-size: 14px;
          font-weight: bold;
          color: #919499;
        }
      }
      .portrait {
        width: 100%;
        box-sizing: border-box;
        padding: 45px 50px;
        display: flex;
        .portrait-left {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
            display: block;
          }
        }
        .portrait-right {
          margin-left: 30px;
          line-height: 28px;
          .user-buy {
            font-size: 14px;
            font-weight: bold;
            color: #43474c;
          }
          .user-tips {
            font-size: 12px;
            font-weight: bold;
            color: #aaaeb3;
          }
        }
      }
      .ordermes {
        box-sizing: border-box;
        padding: 30px 50px 0;
        height: 157px;
        width: 100%;
        .order-title {
          font-size: 16px;
          font-weight: bold;
          color: #43474c;
          line-height: 40px;
        }
        .order-msg {
          display: flex;
          .course-img {
            width: 120px;
            height: 80px;
            background-color: #919499;
            img {
              display: block;
              width: 100%;
              height: 100%;
            }
          }
        }
        .course-info {
          width: 750px;
          margin-left: 24px;
          .course-name {
            font-size: 14px;
            font-weight: bold;
            color: #43474c;
            line-height: 20px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            height: 40px;
          }
          .course-price {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            font-weight: bold;
            color: #494a4d;
          }
        }
      }
      .payway {
        position: relative;
        height: 157px;

        .ivu-radio-group {
          position: absolute;
          display: block;
          width: 886px;
          margin: auto;
          .ivu-radio-wrapper {
            width: 100%;
            height: 60px;
            line-height: 60px;
            background: #f3f6f7;
            display: block;
          }
        }
        > span {
          padding-left: 10px;
          color: rgba(16, 16, 16, 1);
          font-size: 16px;
          text-align: left;
          font-family: SourceHanSansSC-regular;
          font-weight: 600;
        }
      }
      .submitform {
        height: 157px;
        width: 100%;
        text-align: right;
        box-sizing: border-box;
        padding: 0 50px;
        .p1 {
          font-size: 14px;
          font-weight: 400;
          margin-top: 17px;
          > b {
            font-size: 11px;
            color: rgba(240, 66, 61, 1);
          }
          > span {
            font-family: Helvetica;
            font-weight: 700;
            font-size: 26px;
            color: rgba(240, 66, 61, 1);
            font-style: normal;
            letter-spacing: 0px;
            line-height: 30px;
            text-decoration: none;
          }
        }
        .p2 {
          font-family: SourceHanSansSC;
          font-weight: 400;
          font-size: 14px;
          color: rgb(143, 142, 148);
          font-style: normal;
          letter-spacing: 0px;
          line-height: 20px;
          text-decoration: none;
          > a {
            font-family: SourceHanSansSC;
            font-weight: 400;
            font-size: 14px;
            color: rgba(91, 150, 255, 1);
            font-style: normal;
            letter-spacing: 0px;
            line-height: 20px;
            text-decoration: none;
          }
        }
        .ivu-btn {
          width: 162px;
          height: 47px;
          left: 862px;
          top: 62px;
          z-index: 7;
          background-color: rgb(240, 66, 61);
          border-color: rgb(240, 66, 61);
          border-width: 1px;
          border-style: solid;
          color: rgb(255, 255, 255);
          font-size: 18px;
          padding: 0px;
          text-align: center;
          line-height: 26px;
          font-weight: bold;
          font-style: normal;
          opacity: 1;
          float: right;
        }
      }
    }
  }
}
</style>
